using AutoMapper;
using B.S.NewMedical.Api.Read.Application.Command.ContentManagement.Hospital;
using B.S.NewMedical.Api.Read.DTOS.Hospital;
using B.S.NewMedical.Domain.Hospital;
using B.S.NewMedical.ErrorCode;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.NewMedical.Api.Read.Application.Handler.ContentManagement.Hospital
{
    /// <summary>
    /// 获取医院类型列表处理器（用于下拉框）
    /// </summary>
    public class GetHospitalTypesHandler : IRequestHandler<GetHospitalTypesCommand, ApiResult<List<HospitalTypeDto>>>
    {
        private readonly IBaseRepository<HospitalTypeModel> _hospitalTypeRepository;
        private readonly ILogger<GetHospitalTypesHandler> _logger;
        private readonly IMapper _mapper;

        public GetHospitalTypesHandler(
            IBaseRepository<HospitalTypeModel> hospitalTypeRepository,
            ILogger<GetHospitalTypesHandler> logger,
            IMapper mapper)
        {
            _hospitalTypeRepository = hospitalTypeRepository ?? throw new ArgumentNullException(nameof(hospitalTypeRepository));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
            _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
        }

        /// <summary>
        /// 处理获取医院类型列表请求
        /// </summary>
        public async Task<ApiResult<List<HospitalTypeDto>>> Handle(GetHospitalTypesCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始查询医院类型列表");

                // 查询所有未删除的医院类型
                var hospitalTypes = await _hospitalTypeRepository.GetAll()
                    .Where(ht => !ht.IsDeleted)
                    .OrderBy(ht => ht.Id)
                    .ToListAsync(cancellationToken);

                // 映射为DTO
                var hospitalTypeDtos = _mapper.Map<List<HospitalTypeDto>>(hospitalTypes);

                _logger.LogInformation("查询医院类型列表成功，返回 {Count} 条记录", hospitalTypeDtos.Count);

                return new ApiResult<List<HospitalTypeDto>>
                {
                    Code = ApiEnum.Success,
                    Msg = "查询成功",
                    Data = hospitalTypeDtos
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询医院类型列表时发生错误");
                return new ApiResult<List<HospitalTypeDto>>
                {
                    Code = ApiEnum.Error,
                    Msg = "查询失败",
                    Data = new List<HospitalTypeDto>()
                };
            }
        }
    }
}